<template>
  <div>
    <div style="display: flex; flex-wrap: wrap">
      <div style="margin-right: 30px">批量设置</div>
      <!--    <el-button type="primary" @click="editSpec()" link>图片</el-button>-->
      <a style="cursor: pointer; margin-right: 20px" type="primary" @click="editAllSku('price', $event)">售价</a>
      <a style="cursor: pointer; margin-right: 20px" type="primary" @click="editAllSku('cost_price', $event)">成本价</a>
      <a style="cursor: pointer; margin-right: 20px" type="primary" @click="editAllSku('original_price', $event)">原价</a>
      <a style="cursor: pointer; margin-right: 20px" type="primary" @click="editAllSku('stock', $event)">库存</a>
      <a style="cursor: pointer; margin-right: 20px" type="primary" @click="editAllSku('bar_code', $event)">商品编号</a>
      <a style="cursor: pointer; margin-right: 20px" type="primary" @click="editAllSku('weight', $event)">重量</a>
      <a style="cursor: pointer; margin-right: 20px" type="primary" @click="editAllSku('volume', $event)">体积</a>
    </div>
    <el-table :data="skuListValue" stripe style="width: 100%" :editable="true" border>
      <el-table-column prop="sku_name" label="规格" width="150px" align="center"></el-table-column>
      <el-table-column prop="image" label="图片" width="100px" align="center">
        <template #default="scope">
          <div style="display: flex; justify-content: center; align-content: center">
            <ColeAttachment v-model:file="scope.row.image" :width="50" :height="50" />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="售价" width="120px" align="center">
        <template #default="scope">
          <el-input-number :controls="false" type="text" v-model="scope.row.price" clearable
            style="text-align: center; width: 80px" />
        </template>
      </el-table-column>
      <el-table-column prop="cost_price" label="成本价" width="120px" align="center">
        <template #default="scope">
          <el-input-number :controls="false" v-model="scope.row.cost_price" clearable
            style="text-align: center; width: 80px" />
        </template>
      </el-table-column>
      <el-table-column prop="original_price" label="划线价" width="120px" align="center">
        <template #default="scope">
          <el-input-number :controls="false" v-model="scope.row.original_price" clearable
            style="text-align: center; width: 80px" />
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" width="120px" align="center">
        <template #default="scope">
          <el-input-number :controls="false" v-model="scope.row.stock" clearable
            style="text-align: center; width: 80px" />
        </template>
      </el-table-column>
      <el-table-column prop="bar_code" label="商品编号" width="120px" align="center">
        <template #default="scope">
          <el-input type="text" v-model="scope.row.bar_code" clearable style="text-align: center" />
        </template>
      </el-table-column>
      <el-table-column prop="weight" label="重量(KG)" width="120px" align="center">
        <template #default="scope">
          <el-input-number :controls="false" v-model="scope.row.weight" clearable
            style="text-align: center; width: 80px" />
        </template>
      </el-table-column>
      <el-table-column prop="volume" label="体积(M³)" width="120px" align="center">
        <template #default="scope">
          <el-input-number :controls="false" v-model="scope.row.volume" clearable
            style="text-align: center; width: 80px" />
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts" name="ColeSpec">
import { onMounted, ref } from "vue";
import { ElMessageBox } from "element-plus";
import { koiMsgWarning } from "@/utils/koi";
import { watchDeep } from "@vueuse/core";

interface ISkuProps {
  spec: any;
  sku: any;
}

// 子组件接收父组件的值
// withDefaults：设置默认值  defineProps：接收父组件的参数
const props = withDefaults(defineProps<ISkuProps>(), {
  spec: [],
  sku: []
});

const specValue = ref(props.spec);
const skuListValue = ref<any>(props.sku);

watchDeep(
  () => props.spec,
  () => {
    specValue.value = props.spec;
  }
);

const defaultSku = {
  price: 0,
  cost_price: 0,
  bar_code: "",
  stock: 0,
  original_price: 0,
  weight: 0,
  image: "",
  volume: 0
};

onMounted(() => {
  refreshSku();
  watchDeep(
    () => [specValue.value],
    () => {
      refreshSku();
    }
  );
});
const refreshSku = () => {
  if (specValue.value.length <= 0) {
    skuListValue.value = [];
    return;
  }
  let spec = specValue.value
    .map((r: any) => r.item)
    .map((r: any) => r.filter((i: any) => i))
    .filter((r: any) => r.length > 0);
  if (spec.length <= 0) {
    skuListValue.value = [];
    return;
  }
  const sku = skuReduce(spec);
  let newSku = [] as any[];
  for (const index in sku) {
    //判断原来是否存在
    const skuV = Array.isArray(sku[index]) ? sku[index] : [sku[index]];
    const sku_name = skuV.join(" , ");

    const idx = skuListValue.value.findIndex((r: any) => {
      return r.sku_name === sku_name;
    });
    if (idx === -1) {
      newSku.push({
        sku_name: sku_name,
        ...defaultSku
      });
    } else {
      newSku.push({
        sku_name: sku_name,
        ...skuListValue.value[idx]
      });
    }
  }
  skuListValue.value = newSku;
};

//笛卡尔乘积，计算规格
const skuReduce = (arrays: any) => {
  return arrays.reduce((total: any, next: any) => {
    let arr: any = [];
    total.forEach((x: any) => {
      next.forEach((y: any) => {
        arr.push([x].flat().concat([y]));
      });
    });
    return arr;
  });
};

const editAllSku = (key: any, e: any) => {
  ElMessageBox.prompt(
    "你确定批量修改[" + e.target.innerText + "]的值么?该操作会覆盖当前列数据",
    "批量修改:" + e.target.innerText,
    {
      confirmButtonText: "修改",
      cancelButtonText: "关闭"
    }
  )
    .then(({ value }: any) => {
      let pattern = /^[+-]?\d*\.?\d*$/;
      if (key !== "bar_code" && !pattern.test(value)) {
        koiMsgWarning("请输入数字");
        return;
      }
      let newValue: any = value;
      if (key !== "bar_code") {
        newValue = Number(value);
      }

      for (const index in skuListValue.value) {
        skuListValue.value[index][key] = newValue;
      }
    })
    .catch(() => { });
};

const getSkuList = () => {
  return JSON.parse(JSON.stringify(skuListValue.value))
};
const getSpecList = () => {
  return specValue.value;
};
defineExpose({
  getSkuList,
  getSpecList
});
</script>

<style scoped></style>
